#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/types.h>

volatile sig_atomic_t signal_count = 0;


void child_handler(int sig) {
	    if (sig == SIGUSR2) {
		            signal_count++;
			            if (signal_count == 5) {
					                printf("Received 5 signals, child exit!\n");
							            exit(0);
								            }
				        }
}


void parent_handler(int sig) {
	    if (sig == SIGCHLD) {
		            printf("Child terminated.\n");
			            exit(0);
				        }
}

int main() {
	    pid_t pid = fork();
	        
	        if (pid < 0) {
			        perror("fork failed");
				        exit(1);
					    } else if (pid == 0) { // 子进程
						          
						            struct sigaction sa;
							            sa.sa_handler = child_handler;
								            sigemptyset(&sa.sa_mask);
									            sa.sa_flags = 0;
										            
										            if (sigaction(SIGUSR2, &sa, NULL) == -1) {
												                perror("sigaction");
														            exit(1);
															            }
											            
											       
											            while (1) {
													                pause(); // 等待信号
															        }
												        } else { // 父进程
														      
														        struct sigaction sa;
															        sa.sa_handler = parent_handler;
																        sigemptyset(&sa.sa_mask);
																	        sa.sa_flags = 0;
																		        
																		        if (sigaction(SIGCHLD, &sa, NULL) == -1) {
																				            perror("sigaction");
																					                exit(1);
																							        }
																			        
																			     
																			        for (int i = 0; i < 5; i++) {
																					            sleep(2);
																						                if (kill(pid, SIGUSR2) == -1) {
																									                perror("kill");
																											                exit(1);
																													            }
																								        }
																				        
																				    
																				        while (1) {
																						            pause();
																							            }
																					    }
		    
		    return 0;
}
